﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.ModelBinding;
using System.Web.Http.OData;
using System.Web.Http.OData.Routing;
using ICD10WebApiOData.DTO;
using ICD10WebApiOData.Models;

namespace ICD10WebApiOData.Controllers
{
    /*
    To add a route for this controller, merge these statements into the Register method of the WebApiConfig class. Note that OData URLs are case sensitive.

    using System.Web.Http.OData.Builder;
    using ICD10WebApiOData.Models;
    ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
    builder.EntitySet<ICDDetail>("ICDDetail");
    config.Routes.MapODataRoute("odata", "odata", builder.GetEdmModel());
    */
    public class ICDDetailController : ODataController
    {
        private ICD10BEntities db = new ICD10BEntities();

        // GET odata/ICDDetail
        [Queryable]
        public IQueryable<ICDDetail> GetICDDetail()
        {
            return db.ICDDetails;
        }

        // GET odata/ICDDetail(5)
        [Queryable]
        public SingleResult<ICDDetail> GetICDDetail([FromODataUri] int key)
        {
            return SingleResult.Create(db.ICDDetails.Where(icddetail => icddetail.PK == key));
        }

        [HttpPost]
        public List<ICDHeader> GetICDHeaderChapID(ODataActionParameters parameters)
        {
            int chapID = (int)parameters["ID"];            
            var chapter = (from chap in db.ChapterContains
                           where chap.ID == chapID
                           select chap.Include).FirstOrDefault();

            List<ICDHeader> headerList = new List<ICDHeader>();

            ////string[] chapincludes = chapter.Split(',');

            foreach (string item in chapter.ToString().Split(','))
            {
                var result = (from icd in db.ICDDetails
                             where icd.Test == item && icd.TestLevel == 0
                             select new ICDHeader()
                             {
                                 ID = icd.PK,
                                 Header = icd.Test,
                                 Description = icd.TestDesc
                             }).FirstOrDefault();

                headerList.Add(result);
            }

          return headerList;
        }

        [HttpPost]
        public List<ICDHeader> GetICDHeaderByParent(ODataActionParameters parameters)
        {
            string parentID = (string)parameters["ParentID"];
            ////var chapter = (from chap in db.ChapterContains
            ////               where chap.test == chapID
            ////               select chap.Include).FirstOrDefault();

            ////List<ICDHeader> headerList = new List<ICDHeader>();

            ////string[] chapincludes = chapter.Split(',');

         
                var result = from icd in db.ICDDetails
                             where icd.TestParent == parentID && icd.TestLevel != 0
                              select new ICDHeader()
                              {
                                  ID = icd.PK,
                                  Header = icd.Test,
                                  Description = icd.TestDesc
                              };

                return result.ToList();
        }  

        // PUT odata/ICDDetail(5)
        public IHttpActionResult Put([FromODataUri] int key, ICDDetail icddetail)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (key != icddetail.PK)
            {
                return BadRequest();
            }

            db.Entry(icddetail).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ICDDetailExists(key))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return Updated(icddetail);
        }

        // POST odata/ICDDetail
        public IHttpActionResult Post(ICDDetail icddetail)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.ICDDetails.Add(icddetail);
            db.SaveChanges();

            return Created(icddetail);
        }

        // PATCH odata/ICDDetail(5)
        [AcceptVerbs("PATCH", "MERGE")]
        public IHttpActionResult Patch([FromODataUri] int key, Delta<ICDDetail> patch)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            ICDDetail icddetail = db.ICDDetails.Find(key);
            if (icddetail == null)
            {
                return NotFound();
            }

            patch.Patch(icddetail);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ICDDetailExists(key))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return Updated(icddetail);
        }

        // DELETE odata/ICDDetail(5)
        public IHttpActionResult Delete([FromODataUri] int key)
        {
            ICDDetail icddetail = db.ICDDetails.Find(key);
            if (icddetail == null)
            {
                return NotFound();
            }

            db.ICDDetails.Remove(icddetail);
            db.SaveChanges();

            return StatusCode(HttpStatusCode.NoContent);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool ICDDetailExists(int key)
        {
            return db.ICDDetails.Count(e => e.PK == key) > 0;
        }
    }
}
